package com.huatai.exchange.impl;

import com.faneui.common.bean.AbstractLogger;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.DateFormatUtils;
import com.huatai.exchange.dal.dao.ExcFileLoadInfoDAO;
import com.huatai.exchange.dal.model.ExcFileLoadInfo;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.integration.base.service.WorkDayService;
import com.huatai.exchange.integration.support.service.ScheduleBatchService;
import com.huatai.exchange.service.ExcFileLoadInfoService;
import com.huatai.exchange.service.ExcFileLoadRecordService;
import com.huatai.support.facade.bean.schedule.RegisterScheduleBatchReq;
import com.huatai.support.facade.enums.TaskScheduleType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ExcFileLoadInfoServiceImpl extends AbstractLogger implements ExcFileLoadInfoService {

    @Autowired
    private ExcFileLoadInfoDAO excFileLoadInfoDAO ;

    @Autowired
    private WorkDayService workDayService;

    @Value("${server.port}")
    private String businSystemCode;

    @Autowired
    private ExcFileLoadRecordService excFileLoadRecordService;

    @Autowired
    private ScheduleBatchService scheduleBatchService;

    @Override
    public void addExcFileLoadInfo(ExcFileLoadInfo excFileLoadInfo) throws BusinessException {
        try {
            excFileLoadInfoDAO.insert(excFileLoadInfo);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
    }

    @Override
    public ExcFileLoadInfo queryExcFileLoadInfo(String id) throws BusinessException {
        ExcFileLoadInfo info = null;
        try {
            info = excFileLoadInfoDAO.queryById(id);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
        return info;
    }

    @Override
    public List<ExcFileLoadInfo> queryExcFileLoadInfoList(ExcFileLoadInfo excFileLoadInfo) throws BusinessException {
        List<ExcFileLoadInfo> infos = null;
        try {
            infos = excFileLoadInfoDAO.queryByModel(excFileLoadInfo) ;
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
        return infos;
    }

    @Override
    public void modifyExcFileLoadInfo(ExcFileLoadInfo excFileLoadInfo) throws BusinessException {
        try {
            Long num = excFileLoadInfoDAO.updateById(excFileLoadInfo) ;
            if(num == 0 ){
                throw new BusinessException("更新记录为0，失败") ;
            }
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
    }

    @Override
    public List<ExcFileLoadInfo> queryExcFileNeedLoadInfoList() throws BusinessException {
        ExcFileLoadInfo excFileLoadInfo = new ExcFileLoadInfo();
        excFileLoadInfo.setStatus(com.faneui.common.utils.Constants.boolean_true);
        return queryExcFileLoadInfoList(excFileLoadInfo);
    }

    @Override
    public void modifyFileLoadInfoWorkDate(String id, String newNextDate, String oldNextDate) throws BusinessException {
        try {
            Long num = excFileLoadInfoDAO.updateNextDate(id,newNextDate,oldNextDate) ;
            if(num == 0 ){
                throw new BusinessException("更新记录为0，失败") ;
            }
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void createScheduleBatch(ExcFileLoadInfo loadInfo,String occurDate) throws BusinessException {
        String nowDate = DateFormatUtils.yyyyMMdd.format(new Date());
        if (occurDate.equals(nowDate)
                && Integer.valueOf(DateFormatUtils.HHmmss.format(new Date())) < Integer.valueOf(loadInfo.getStartTime())) {
            logger.info("时间未到");
            return;
        }
        String interval = loadInfo.getInterval();
        //
        String nextDate = workDayService.getWorkDayNextWorkDay(occurDate);
        if (Contents.interval_first_workdate.equals(interval)) {
            nextDate = workDayService.getNextFirstWorkDay(occurDate);
        }else if(Contents.interval_naturaldate.equalsIgnoreCase(interval)){
            nextDate = workDayService.getNextNatureDay(occurDate) ;
        }
        // 先更新日期 ,如果 批次创建失败 ，则会回滚
        modifyFileLoadInfoWorkDate(loadInfo.getId(),nextDate,occurDate);

        RegisterScheduleBatchReq req = new RegisterScheduleBatchReq();


        req.setTaskName("加载"+loadInfo.getFileName() + "数据或文件");
        req.setBusinSystemCode(businSystemCode);
        req.setBusinId(Contents.busin_load_file_id + loadInfo.getId());
        // 参数编辑
//                    req.setProperties(task.getJsonProperties());
        req.setSystemPort(businSystemCode);

        req.setHttpMethod("GET");
        // 增加日期
        req.setInterfaceUrl(Contents.load_excute_url + loadInfo.getId() + "?occurDate=" + occurDate);

        // 增加
        req.setTaskScheduleType(TaskScheduleType.day_one);

        req.setDealInterval(10);   // 清算流程 10秒钟 间隔时间 ，1小时最大可执行 360
        req.setErrorTimes(360 * 6);       // 配置至少 6个小时

        scheduleBatchService.registerScheduleBatch(req);
    }

}
